<template>
  <div class="app-container">
    <div v-has-perm="['nljs_form_category_view']" class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="categoryName" label="分类名称">
          <el-input v-model="queryParams.categoryName" placeholder="分类名称" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
          <el-button v-has-perm="['nljs_form_category_del']" type="danger" :disabled="!batchIds.length" plain
            :icon="Delete" @click="delBatchIds">
            批量删除
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="app-content">
      <div class="title-area">
        <el-button v-has-perm="['nljs_form_category_add']" type="primary" plain :icon="Plus" @click="addForm">
          新增表单分类
        </el-button>
      </div>
      <el-table ref="dataTableRef" height="calc(100vh - 350px)" v-loading="loading" :data="tableData"
        highlight-current-row border @selection-change="handleSelectionChange">
        <el-table-column v-has-perm="['nljs_form_category_del']" type="selection" width="55" align="center" />
        <el-table-column label="分类名称" prop="categoryName" min-width="160">
          <template #default="scope">
            <el-button type="primary" link @click="jumpFormList(scope.row)">
              {{ scope.row.categoryName }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="分类编码" prop="categoryCode" min-width="160" />
        <el-table-column label="分类描述" prop="description" min-width="160" />
        <el-table-column label="状态" prop="status" width="120">
          <template #default="scope">
            <el-tag :type="statusTag[scope.row.status]">
              {{ statusMap[scope.row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180" />
        <el-table-column label="创建人" prop="createBy" width="180" />
        <el-table-column label="排序" prop="displayOrder" width="80" />
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <!-- <el-button
              link
              type="primary"
              :icon="Document"
              size="small"
              @click="goCatList(scope.row)"
            >
              查看
            </el-button> -->
            <el-button v-has-perm="['nljs_form_category_edit']" link type="success" :icon="Edit" size="small"
              @click="editCat(scope.row)">
              修改
            </el-button>
            <el-button v-has-perm="['nljs_form_category_del']" link type="danger" :icon="Delete" size="small"
              @click="delCat(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div v-if="pageTotal > 0" class="pager-container">
      <pagination v-model:total="pageTotal" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        @pagination="handleQuery" />
    </div>

    <el-dialog v-model="dialogVisible" title="表单分类" width="500" :close-on-click-modal="false" @close="reset">
      <div class="year">
        <el-form ref="formRef" :model="categoryForm" :rules="categoryRules" label-width="auto">
          <el-form-item label="分类名称" prop="categoryName">
            <el-input v-model="categoryForm.categoryName" />
          </el-form-item>
          <el-form-item label="分类编码" prop="categoryCode">
            <el-input v-model="categoryForm.categoryCode" />
          </el-form-item>
          <el-form-item label="分类描述" prop="description">
            <el-input v-model="categoryForm.description" type="textarea" maxlength="500" :rows="2" />
          </el-form-item>
          <el-form-item label="显示顺序" prop="displayOrder">
            <el-input-number v-model="categoryForm.displayOrder" :min="0" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="categoryForm.status">
              <el-radio label="禁用" :value="0"></el-radio>
              <el-radio label="启用" :value="1"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="reset">取消</el-button>
          <el-button size="small" type="primary" @click="confirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import FormAPI from '@/api/batch/form.api';
import { Plus, Document, Edit, Delete } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';

interface ParamsType extends PageQuery {
  pageNum: number;
  pageSize: number;
  [key: string]: any;
}

const queryFormRef = ref<FormInstance>();
const pageTotal = ref(0);
const queryParams = reactive<ParamsType>({
  pageNum: 1,
  pageSize: 10,
  categoryName: undefined,
});
const loading = ref(false);
const batchIds = ref<number[] | string[]>([]);
const tableData = ref<object[]>([]);
const statusTag = reactive<any>({
  0: 'danger',
  1: 'success',
});

const statusMap = reactive<any>({
  0: '禁用',
  1: '启用',
});

const router = useRouter(); // 路由跳转
const route = useRoute(); // 获取路由参数
// const { params, query } = route;

const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const categoryForm = reactive<any>({
  id: undefined,
  categoryName: '',
  categoryCode: '',
  description: '',
  displayOrder: 0,
  status: 1,
});
const categoryRules: FormRules = {
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500', trigger: 'blur' },
  ],
  categoryCode: [
    { required: true, message: '请输入分类编码', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500', trigger: 'blur' },
  ],
};

const handleQuery = () => {
  loading.value = true;
  const params = {
    current: queryParams.pageNum,
    size: queryParams.pageSize,
    categoryName: queryParams.categoryName,
  };
  FormAPI.getFormList(params)
    .then((data: any) => {
      const { records = [], total = 0 } = data;
      tableData.value = records;
      pageTotal.value = total;
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
    });
};

const handleResetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
};

const handleSelectionChange = (val: any) => {
  batchIds.value = val.map((item: any) => item.id);
};

// 批量删除
const delBatchIds = () => {
  ElMessageBox.confirm('确认删除?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      FormAPI.batchDel(batchIds.value)
        .then((res) => {
          ElMessage.success('批量删除成功!');
          handleQuery();
        })
        .catch((err) => {
          ElMessage.error('批量删除失败!');
        });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
};

const jumpFormList = (row: any) => {
  router.push({
    path: '/form/definition',
    query: {
      categoryId: row.id,
      name: row.categoryName,
    },
  });
};

const goCatList = (row: any) => { };
const editCat = (row: any) => {
  FormAPI.getBatchDetail(row.id)
    .then((res: any) => {
      dialogVisible.value = true;
      categoryForm.id = res.id;
      categoryForm.categoryName = res.categoryName;
      categoryForm.categoryCode = res.categoryCode;
      categoryForm.description = res.description;
      categoryForm.displayOrder = res.displayOrder;
      categoryForm.status = res.status;
    })
    .catch((err) => {
      ElMessage.error('批量删除失败!');
    });
};
const delCat = (row: any) => {
  ElMessageBox.confirm('确认删除?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      FormAPI.delForm(row.id).then((data: any) => {
        ElMessage.success('删除成功!');
        // ElMessage({
        //   message: 'This is a message.',
        //   grouping: true, // 内容相同的 message 将被合并
        //   type: 'success',
        // });
        handleQuery();
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
};

const addForm = () => {
  dialogVisible.value = true;
};
const reset = () => {
  dialogVisible.value = false;
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
  categoryForm.id = undefined;
  categoryForm.categoryName = '';
  categoryForm.categoryCode = '';
  categoryForm.description = '';
  categoryForm.displayOrder = 0;
  categoryForm.status = 1;
};
const confirm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      const params = { ...categoryForm };
      if (categoryForm.id) {
        FormAPI.editFormCategory(params).then((data: any) => {
          ElMessage.success('编辑成功!');
          reset();
          handleQuery();
        });
      } else {
        FormAPI.addFormCategory(params).then((data: any) => {
          ElMessage.success('新增成功!');
          reset();
          queryParams.pageNum = 1;
          handleQuery();
        });
      }
    }
  });
};

onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
.title-area {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 15px;
}
</style>
